package iris

import (
	"fmt"
	"github.com/casdoor/casdoor-go-sdk/auth"
	"github.com/golang-jwt/jwt/v4"
	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/logger"
	"github.com/kataras/iris/v12/mvc"
	"gluenet/internal/pkg/infra"
	"gluenet/internal/pkg/infra/prepare"
	"strings"
)

var App *iris.Application

func init() {
	App = iris.New()
	//App.Use(recover.New())
}

func Run() error {
	//var login *domain
	//prepare.FetchDependency(&login)

	App.Use(logger.New())
	party := App.Party("/apis", func(ctx iris.Context) {
		//fmt.Printf("auth .....\n")

		//token := ctx.GetHeader("token")
		//
		////fmt.Printf("token %v .....\n",token)
		//auth, err := login.Auth(token)
		//if err != nil {
		//	ctx.JSON(infra.ResponseReqErr(err, nil))
		//	return
		//}

		//bts,_ := json.Marshal(auth)
		//fmt.Printf("auth: %s.....\n",bts)

		//_ = strings.ReplaceAll(auth.Id, "-", "")
		//ctx.Values().Set("admin", auth.IsAdmin)
		ctx.Values().Set("user_id", "001")
		ctx.Values().Set("group_id", 100)
		ctx.Values().Set("auth_level", 2)
		ctx.Next()
	})
	//App.Get("/login", func(ctx iris.Context) {
	//	//fmt.Printf("login .....\n")
	//	code := ctx.URLParam("code")
	//	state := ctx.URLParam("state")
	//	token, err := login.Login(code, state)
	//	if err != nil {
	//		ctx.JSON(infra.ResponseReqErr(err, nil))
	//		return
	//	}
	//	ctx.JSON(infra.ResponseOK(token))
	//})
	App.Get("/list", func(ctx iris.Context) {
		ctx.JSON(infra.ResponseOK(infra.ListIrisRouter()))
	})

	App.Get("/token", func(ctx iris.Context) {
		id := ctx.URLParam("id")
		key, _ := jwt.ParseRSAPrivateKeyFromPEM([]byte(infra.JPrivateKey))
		cl := auth.Claims{}
		cl.Id = id
		cl.IsAdmin = true
		accessToken, _ := jwt.NewWithClaims(jwt.SigningMethodRS256, cl).SignedString(key)
		ctx.JSON(infra.ResponseOK(accessToken))
		return
	})
	authControllers := prepare.FetchAllAuthControllers()
	for k, v := range authControllers {
		ks := strings.Split(k.String(), ".")
		name := strings.ToLower(ks[len(ks)-1])
		mvc.New(party.Party(fmt.Sprintf("/%v/", name))).Handle(v)
	}

	party2 := App.Party("/api")
	controllers := prepare.FetchAllControllers()
	for k, v := range controllers {
		ks := strings.Split(k.String(), ".")
		name := strings.ToLower(ks[len(ks)-1])
		mvc.New(party2.Party(fmt.Sprintf("/%v/", name))).Handle(v)
	}

	for _, v := range App.GetRoutes() {
		infra.RegisterRouter("web", v.Path, v.Method)
	}
	infra.RegisterRouter("web", "/login", iris.MethodGet)

	go App.Run(iris.Addr(":8080"))
	return nil
}

//func BindController(root string, iris-controller interface{}) {
//	router := app.Party(root)
//	mvc.New(router).Handle(iris-controller)
//}
